package com.ltkj.coupon.service.impl;

import com.alibaba.fastjson.JSON;
import com.ltkj.common.core.constant.HttpStatus;
import com.ltkj.common.core.exception.ServiceException;
import com.ltkj.common.core.utils.DateUtils;
import com.ltkj.common.core.utils.HotelCodeUtils;
import com.ltkj.common.core.utils.StringUtils;
import com.ltkj.common.core.utils.bean.BeanUtils;
import com.ltkj.common.core.web.domain.AjaxResult;
import com.ltkj.common.security.utils.SecurityUtils;
import com.ltkj.coupon.domain.TCouponTemp;
import com.ltkj.coupon.domain.TCouponUser;
import com.ltkj.coupon.domain.dto.CouponUserPageQueryDTO;
import com.ltkj.coupon.domain.dto.TCouponUserAddDTO;
import com.ltkj.coupon.domain.vo.TCouponUserPageVo;
import com.ltkj.coupon.mapper.TCouponMapper;
import com.ltkj.coupon.mapper.TCouponTempMapper;
import com.ltkj.coupon.mapper.TCouponUserMapper;
import com.ltkj.coupon.service.ITCouponUserService;
import com.ltkj.system.api.RemoteUserService;
import com.ltkj.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户优惠券Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-09-21
 */
@Service
public class TCouponUserServiceImpl implements ITCouponUserService 
{
    @Autowired
    private TCouponUserMapper tCouponUserMapper;
    @Autowired
    private TCouponMapper tcouponMapper;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private TCouponTempMapper tCouponTempMapper;

    /**
     * 查询用户优惠券
     * 
     * @param id 用户优惠券主键
     * @return 用户优惠券
     */
    @Override
    public TCouponUser selectTCouponUserById(Long id)
    {
        return tCouponUserMapper.selectTCouponUserById(id);
    }

    /**
     * 查询用户优惠券列表
     * 
     * @param tCouponUser 用户优惠券
     * @return 用户优惠券
     */
    @Override
    public List<TCouponUser> selectTCouponUserList(TCouponUser tCouponUser)
    {
        return tCouponUserMapper.selectTCouponUserList(tCouponUser);
    }

    /**
     * 新增用户优惠券
     * 
     * @param tCouponUser 用户优惠券
     * @return 结果
     */
    @Override
    public int insertTCouponUser(TCouponUser tCouponUser)
    {
        tCouponUser.setCreateTime(DateUtils.getNowDate());
        return tCouponUserMapper.insertTCouponUser(tCouponUser);
    }

    @Override
    public int insertTCouponUserV2(TCouponUserAddDTO tCouponUserAddDTO) {
        //票数量是否还有
        TCouponTemp tCouponTemp = tCouponTempMapper.selectTCouponTempById(tCouponUserAddDTO.getCouponTempId());
        if(tCouponTemp==null){
            throw new ServiceException("优惠券不存在!");
        }
        if(tCouponTemp.getQuantityResidue()<=0){
            throw new ServiceException("优惠券数量不足!");
        }
        //判断当前时间是否在时效之前
        int compareToDateTime = DateUtils.getCompareToDateTime(tCouponTemp.getEffectiveEndTime());
        if(compareToDateTime<0){
            throw new ServiceException("优惠券可用时间已过!");
        }
        //查询此手机号的信息
        AjaxResult infoByPhone = remoteUserService.getInfoByPhone(tCouponUserAddDTO.getMobile());
        int code = (int) infoByPhone.get("code");
        if(code== HttpStatus.SUCCESS){
            Object object = infoByPhone.get("data");
            SysUser sysUser = JSON.parseObject(JSON.toJSONString(object), SysUser.class);
            //判断此手机号是否已经存在
            int i = tcouponMapper.queryCouponUserByCouponTempId(tCouponUserAddDTO.getCouponTempId(), sysUser.getUserId());
            if(i>0){
                throw new ServiceException("同一人不可重复添加此优惠券!");
            }
            TCouponUser tCouponUser = BeanUtils.copy(tCouponTemp, TCouponUser.class);
            tCouponUser.setUserId(sysUser.getUserId());
            tCouponUser.setCouponTempId(tCouponUserAddDTO.getCouponTempId());
            tCouponUser.setCodeNo(HotelCodeUtils.buildTicCouponNo());
            tCouponUser.setStatus("0");
            tCouponUser.setIsDel("0");
            String username = SecurityUtils.getLoginUser().getUsername();
            tCouponUser.setCreateBy(username);
            tCouponUser.setCouponAmount(tCouponTemp.getCouponAmout());
            tCouponUser.setFullAmount(tCouponTemp.getFullAmount());
            tCouponUser.setCreateTime(DateUtils.getNowDate());
            int i1 = tCouponUserMapper.insertTCouponUser(tCouponUser);
            tCouponTemp.setQuantityResidue(tCouponTemp.getQuantityResidue()-1);
            tCouponTemp.setUpdateBy(username);
            tCouponTemp.setUpdateTime(DateUtils.getNowDate());
            tCouponTempMapper.updateTCouponTemp(tCouponTemp);
            return i1;

        }else {
            throw new ServiceException((String) infoByPhone.get("msg"));
        }

    }

    @Override
    public String insertTCouponUserList(List<TCouponUserAddDTO> tCouponUserAddDTO,Long couponTempId) {

        if (StringUtils.isNull(tCouponUserAddDTO) || tCouponUserAddDTO.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        TCouponTemp tCouponTemp = tCouponTempMapper.selectTCouponTempById(couponTempId);
        if(tCouponTemp==null){
            throw new ServiceException("优惠券不存在!");
        }
        if(tCouponTemp.getQuantityResidue()<=0){
            throw new ServiceException("优惠券数量不足!");
        }
        //判断当前时间是否在时效之前
        int compareToDateTime = DateUtils.getCompareToDateTime(tCouponTemp.getEffectiveEndTime());
        if(compareToDateTime<0){
            throw new ServiceException("优惠券可用时间已过!");
        }
        int successNum = 0;
        int failureNum = 0;
        Long quantityResidue=tCouponTemp.getQuantityResidue();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String username = SecurityUtils.getLoginUser().getUsername();
        for (TCouponUserAddDTO dto : tCouponUserAddDTO)
        {
            //查询此手机号的信息
            AjaxResult infoByPhone = remoteUserService.getInfoByPhone(dto.getMobile());
            int code = (int) infoByPhone.get("code");
            if(code== HttpStatus.SUCCESS){
                Object object = infoByPhone.get("data");
                SysUser sysUser = JSON.parseObject(JSON.toJSONString(object), SysUser.class);
                if (sysUser == null) {
                    throw new ServiceException("导入的用户不存在，请检查该用户手机号是否登录过");
                }
                //判断此手机号是否已经存在
                int i = tcouponMapper.queryCouponUserByCouponTempId(couponTempId, sysUser.getUserId());
                if(i>0){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手机号 " + dto.getMobile() + "同一人不可重复添加此优惠券!");
                }
                if(quantityResidue<=0){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手机号 " + dto.getMobile() + "优惠券数量不足!");
                }else{
                    quantityResidue=quantityResidue-1;

                    tCouponTemp.setQuantityResidue(quantityResidue);
                    tCouponTemp.setUpdateBy(username);
                    tCouponTemp.setUpdateTime(DateUtils.getNowDate());
                    tCouponTempMapper.updateTCouponTemp(tCouponTemp);

                    TCouponUser tCouponUser = BeanUtils.copy(tCouponTemp, TCouponUser.class);
                    tCouponUser.setUserId(sysUser.getUserId());
                    tCouponUser.setCodeNo(HotelCodeUtils.buildTicCouponNo());
                    tCouponUser.setCouponTempId(couponTempId);
                    tCouponUser.setCouponAmount(tCouponTemp.getCouponAmout());
                    tCouponUser.setFullAmount(tCouponTemp.getFullAmount());
                    tCouponUser.setStatus("0");
                    tCouponUser.setIsDel("0");

                    tCouponUser.setCreateBy(username);
                    tCouponUser.setCreateTime(DateUtils.getNowDate());
                    int i1 = tCouponUserMapper.insertTCouponUser(tCouponUser);
                    successNum++;

                    successMsg.append("<br/>" + successNum + "、手机号 " + dto.getMobile() + " 导入成功");
                }

            }else {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、手机号 " + dto.getMobile() + " 不存在");
            }


        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "导入成功:"+successNum+"条"+"<br/>"+"很抱歉，导入失败:"+failureNum+"条"+"<br/>"+"错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }



    /**
     * 修改用户优惠券
     * 
     * @param tCouponUser 用户优惠券
     * @return 结果
     */
    @Override
    public int updateTCouponUser(TCouponUser tCouponUser)
    {
        tCouponUser.setUpdateTime(DateUtils.getNowDate());
        return tCouponUserMapper.updateTCouponUser(tCouponUser);
    }

    @Override
    public int cancel(Long id) {
        TCouponUser tCouponUser = tCouponUserMapper.selectTCouponUserById(id);
        if(tCouponUser==null){
            throw new ServiceException("此信息不存在!");
        }
        tCouponUser.setStatus("-1");
        String username = SecurityUtils.getLoginUser().getUsername();
        tCouponUser.setUpdateBy(username);
        tCouponUser.setUpdateTime(DateUtils.getNowDate());

        return tCouponUserMapper.updateTCouponUser(tCouponUser);
    }

    /**
     * 批量删除用户优惠券
     * 
     * @param ids 需要删除的用户优惠券主键
     * @return 结果
     */
    @Override
    public int deleteTCouponUserByIds(Long[] ids)
    {
        String username = SecurityUtils.getLoginUser().getUsername();
        int num=0;
        if(ids!=null&&ids.length>0){
            for(int i=0;i<ids.length;i++){
                TCouponUser tCouponUser = tCouponUserMapper.selectTCouponUserById(ids[i]);
                if(tCouponUser==null){
                    throw new ServiceException("此信息不存在!");
                }
                tCouponUser.setIsDel("1");
                tCouponUser.setUpdateBy(username);
                tCouponUser.setUpdateTime(DateUtils.getNowDate());
                 tCouponUserMapper.updateTCouponUser(tCouponUser);
                 num++;
            }

        }


        return num;
    }

    /**
     * 删除用户优惠券信息
     * 
     * @param id 用户优惠券主键
     * @return 结果
     */
    @Override
    public int deleteTCouponUserById(Long id)
    {
        return tCouponUserMapper.deleteTCouponUserById(id);
    }

    @Override
    public List<TCouponUserPageVo> selectTCouponUserPage(CouponUserPageQueryDTO queryDTO) {
        List<TCouponUserPageVo> list = tcouponMapper.selectTCouponUserPage(queryDTO);
        return list;
    }
}
